'''
顏色轉換
常用功能 BGR<->Gray ��  BGR<->HSV
flag: cv2.COLOR_BGR2GRAY   cv2.COLOR_BGR2HSV
'''
import cv2
import numpy as np
import time

cap = cv2.VideoCapture(0)  #open camera

# set the threshold of blue
upper = np.array([180, 255, 255])
lower = np.array([120, 40, 40])

kernel = np.ones((5,5),np.uint8)

while True:
    # get a frame from camera
    ret, frame = cap.read()
    if ret == False:
        print('獲取圖像失敗')
        time.sleep(1)
        continue
    # convert from BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)



    # get the mask of blue by threshold
    mask = cv2.inRange(hsv, lower, upper)
    # 開運算去除周圍噪點
    mask1 = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel,iterations=1)
    mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, kernel,iterations= 5)
    mask1 = cv2.dilate(mask1, kernel, iterations = 2)

    res = cv2.bitwise_and(frame, frame, mask=mask1)

    cv2.imshow('frame', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('mask1', mask1)
    cv2.imshow('res', res)

    if cv2.waitKey(5) == ord(' '):
        break
    pass

cv2.destroyAllWindows()
cap.release()
